<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org">

  <title>new</title>
  <link href="../cppreference.css" rel="stylesheet" type="text/css">
</head>

<body>
<table>
  <tr>
  <td>
  <div class="body-content">

  <div class="header-box">
    <a href="../index.html">cppreference.com</a> &gt; <a href=
    "index.html">C/C++ Keywords</a> &gt; <a href="new.html">new</a>
  </div>

  <div class="name-format">
    new
  </div>

  <div class="syntax-name-format">
    Syntax:
  </div>
  <pre class="syntax-box">
  pointer = new type;
  pointer = new type( initializer );
  pointer = new type[size];
  pointer = new( arg-list ) type...
</pre>

  <p>The new operator (valid only in C++) allocates a new chunk of
  memory to hold a variable of type <em>type</em> and returns a
  pointer to that memory.  An optional initializer can be used to
  initialize the memory.  Allocating arrays can be accomplished by
  providing a <em>size</em> parameter in brackets.</p>

  <p>The optional <em>arg-list</em> parameter can be used with any of
  the other formats to pass a variable number of arguments to an
  overloaded version of new().  For example, the following code shows
  how the new() function can be overloaded for a class and then passed
  arbitrary arguments:</p>

  <pre class="example-code">
  class Base {
  public:
    Base() { }

    void *operator new( unsigned int size, string str ) {
      cout &lt;&lt; "Logging an allocation of " &lt;&lt; size &lt;&lt; " bytes for new object '" &lt;&lt; str &lt;&lt; "'" &lt;&lt; endl;
      return malloc( size );
    }

    int var;
    double var2;
  };

  ...

  Base* b = new ("Base instance 1") Base;
</pre>

  <p>If an int is 4 bytes and a double is 8 bytes, the above code
  generates the following output when run:</p>

  <pre class="example-code">
  Logging an allocation of 12 bytes for new object 'Base instance 1'
</pre>

  <div class="related-name-format">
    Related topics:
  </div>

  <div class="related-content">
    <a href="delete.html">delete</a><br>
    (Standard C Memory) <a href="../stdmem/free.html">free</a><br>
    (Standard C Memory) <a href="../stdmem/malloc.html">malloc</a>
  </div>
  </div>
  </td>
  


  </tr>
  </table>
</body></html>
